package com.imooc.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.imooc.enums.Sex;
import com.imooc.mapper.UsersMapper;
import com.imooc.pojo.Users;
import com.imooc.pojo.bo.UserBO;
import com.imooc.service.UserService;
import com.imooc.utils.DateUtil;
import com.imooc.utils.MD5Utils;
import java.util.Date;
import lombok.AllArgsConstructor;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {

  private static final String USER_FACE = "http://122.152.205.72:88/group1/M00/00/05/CpoxxFw_8_qAIlFXAAAcIhVPdSg994.png";

  private final UsersMapper usersMapper;

  private final Sid sid;

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.SUPPORTS)
  @Override
  public boolean queryUsernameIsExist(String username) {
    return ObjectUtil.isNotNull(
        usersMapper.selectOne(Wrappers.<Users>lambdaQuery().eq(Users::getUsername, username)));
  }


  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public Users createUser(UserBO userBO) {
//        try {
//            Thread.sleep(3500);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    String userId = sid.nextShort();
    Users user = new Users();
    user.setId(userId);
    user.setUsername(userBO.getUsername());
    try {
      user.setPassword(MD5Utils.getMD5Str(userBO.getPassword()));
    } catch (Exception e) {
      e.printStackTrace();
    }
    // 默认用户昵称同用户名
    user.setNickname(userBO.getUsername());
    // 默认头像
    user.setFace(USER_FACE);
    // 默认生日
    user.setBirthday(DateUtil.stringToDate("1900-01-01"));
    // 默认性别为 保密
    user.setSex(Sex.secret.type);
    user.setCreatedTime(new Date());
    user.setUpdatedTime(new Date());
    usersMapper.insert(user);
    return user;
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.SUPPORTS)
  @Override
  public Users queryUserForLogin(String username, String password) {
//        try {
//            Thread.sleep(2500);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    return usersMapper.selectOne(
        Wrappers.<Users>lambdaQuery().eq(Users::getUsername, username)
            .eq(Users::getPassword, password));
  }
}